<?php
declare(strict_types=1);

namespace App\Controller\Api\V1;

use App\Job\ExampleJob;
use App\Model\LiveChargeOrder;
use App\Model\Talk\TalkRecords;
use App\Service\QueueService;
use App\Service\RockyPayLibrary2;
use App\Service\TalkMessageService;
use App\Service\UserService;
use App\Middleware\JWTAuthMiddleware;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\AsyncQueue\Driver\DriverInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketServer\Sender;

/**
 * class SystemController
 * @package App\Controller\Api\V1
 * @Controller(prefix="/api/v1/system")
 */
class SystemController extends CController
{

    /**
     * @Inject
     * @var Sender
     */
    public $sender;

    /**
     * @Inject()
     * @var QueueService
     */
    private $QueueService;

    /**
     * 微信支付回调
     *
     * @RequestMapping(path="charge/{id}/wx-notify", methods="post")
     */
    public function chargeNotify()
    {

        $id = $this->request->route('id');

        $params = $this->request->all();
        info('wxchargenofity', $params);

        $rechargeOrder = LiveChargeOrder::where('id', $id)->where('status', 100)->first();
        if (empty($rechargeOrder)) {
            return 'SUCCESS';
        }
        $paymentMechod = data_get($rechargeOrder, 'payment_method', 'wx_mp');

        $tmp = explode('_', $paymentMechod);
        if (data_get($tmp, 0, 'wx') == 'wx') {
            $driver = 'wechat';
        } else {
            throw new \LogicException('error', 100);
        }
        $rockyPay = new RockyPayLibrary2([], $driver);
        $notifyInfo = $rockyPay->wxMpNotify(data_get($tmp, 1, 'mp'), $params);
        info('order微信支付 解析', [$notifyInfo]);


        if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
            $upd['amount'] = $notifyInfo['total_fee'] / 100;
            $data['status'] = 200;
            $data['payment_txn'] = $notifyInfo['transaction_id'];
            $rechargeOrder->update($data);
            UserService::commonTransaction(data_get($rechargeOrder, 'user_id', ''), data_get($rechargeOrder, 'points', ''), data_get($rechargeOrder, 'id', ''), 'live_charge_order', '充值'.data_get($rechargeOrder, 'product_name', ''));
        }

        return 'SUCCESS';
    }


    /**
     * app查付款
     *
     * @RequestMapping(path="charge-order", methods="get")
     *
     */
    public function chargeOrder() : ResponseInterface
    {
        $params = $this->request->inputs(['id']);
        $id = data_get($params,'id',0);
        $order = LiveChargeOrder::where('id', '=', $id)
            ->select('id', 'status')
            ->first();

        $isPaid = 0;
        if (data_get($order, 'status', 0) >= 200) {
            $isPaid = 1;
        }

        return $this->response->success(['is_paid' => $isPaid]);
    }

    /**
     * 微信支付回调
     *
     * @RequestMapping(path="wsclose", methods="post")
     */
    public function close(RequestInterface $request)
    {
        $params = $request->all();


        $fd = data_get($params, 'client_id', '');
        try {
            $res = $this->sender->disconnect((int)$fd);
        } catch (\Exception $e) {
            throw new \LogicException('消息转发失败', 1005);
        }
        return $res;
    }

    /**
     * 微信支付回调
     *
     * @RequestMapping(path="callback", methods="post")
     */
    public function callback(RequestInterface $request)
    {
        $params = $request->all();

        info('zz');
        return 'zzzzzz';

        $fd = data_get($params, 'client_id', '');
        try {
            $res = $this->sender->disconnect((int)$fd);
        } catch (\Exception $e) {
            throw new \LogicException('消息转发失败', 1005);
        }
        return $res;
    }


    /**
     * wangtest
     *
     * @RequestMapping(path="wangtest", methods="get")
     */
    public function wangtest(RequestInterface $request)
    {
        $params = $request->all();
        $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('gift_rank');
        $a = [
            'group@hyperf.io',
            'https://doc.hyperf.io',
            'https://www.hyperf.io',
        ];
        return $driver->push(new ExampleJob($a), 0);
        $r = $this->QueueService->push([
            'group@hyperf.io',
            'https://doc.hyperf.io',
            'https://www.hyperf.io',
        ]);

        return $r;

        info('zz');
        return 'zzzzzz';

        $fd = data_get($params, 'client_id', '');
        try {
            $res = $this->sender->disconnect((int)$fd);
        } catch (\Exception $e) {
            throw new \LogicException('消息转发失败', 1005);
        }
        return $res;
    }

    /**
     * 苹果内购验证
     *
     * @RequestMapping(path="validate_apple_pay", methods="post")
     */
    public function validateApplePay(RequestInterface $request)
    {
        $params = $request->all();
        info('内购参数', $params);
        $receipt = data_get($params, 'receipt',''); //支付票据
        $sandbox = data_get($params, 'sandbox',0); //是否是沙盒
        $order_id = data_get($params, 'order_id',0); //订单号
        //验证参数
        if (strlen($receipt) < 20 || empty($order_id)) {
            throw new \LogicException('非法参数!', 101);
        }
        $rechargeOrder = LiveChargeOrder::where('id', $order_id)->where('status', 100)->first();
        if(empty($rechargeOrder)) throw new \LogicException('找不到订单', 100);
        //票据信息
        $postData = json_encode([
            "receipt-data" => $receipt
        ]);
        $url_buy = "https://buy.itunes.apple.com/verifyReceipt"; //正式购买地址
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"; //沙盒购买地址
        $url = $sandbox ? $url_sandbox : $url_buy;
        // 请求验证
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($res, true);

        info('内购结果', [$res]);
        if (data_get($res,'status',-99) != 0) {
            throw new \LogicException('内购验证失败', 101);
        }
        //成功
        $rechargeOrder->update([
                'status'=>200,
                'payment_method'=>'applepay',
            ]);
        UserService::commonTransaction(data_get($rechargeOrder, 'user_id', ''), data_get($rechargeOrder, 'points', ''), data_get($rechargeOrder, 'id', ''), 'live_charge_order', '充值'.data_get($rechargeOrder, 'product_name', ''));
        return $this->response->success(['msg'=>'验证成功了']);
    }

    /**
     * 送礼物通知
     *
     * @RequestMapping(path="gift-notify", methods="post")
     */
    public function giftNotify(RequestInterface $request)
    {
        $params = $request->all();
        info('送礼通知', $params);
        $c = new TalkMessageService();
        $insert = TalkRecords::find(data_get($params, 'insert_id', ''));
        $c->handle($insert, ['text' => '[礼物消息]']);

        $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('gift_rank');
        $a = [
            'receiver_id' => data_get($params, 'receiver_id', 3),
            'sender_id' => data_get($params, 'receiver_id', ''),
        ];
        return $driver->push(new ExampleJob($a), 0);
    }
}
